package pnu.ssm.drawchinese;

import java.util.Random;

import pnu.ssm.chinese.ChineseCharacter;
import pnu.ssm.chinese.ChineseHelper;
import pnu.ssm.chinese.Stroke;
import pnu.ssm.http.HttpConnector;
import pnu.ssm.key.Key;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class DrawMainBoard extends View {

	public static final String TAG = "DrawMainBoard";
	
	public interface NextChineseListener{
		void nextChinese(String meaning, String level);
	}
	public static void setOnNextChineseListener(NextChineseListener nextChineseListenerF){
		nextChineseListener = nextChineseListenerF;
	};
	public static NextChineseListener nextChineseListener;
	
	Paint chineseBlush;
	Path mPath;
	int alpha = 200;
	int strokeWidth = 50;
	int maxCount = 47;
	boolean loaded = false;
	final int[] initRGB = new int[] {253,0,0};
	final int[] finalRGB = new int[] {254,0,0};
	final int[] centerRGB = new int[] {255,0,0};
	boolean checkInitPoint = false;
	boolean checkCenterPoint = false;
	boolean checkFinalPoint = false;
	boolean reset = false;
	boolean reload = false;
	
	Context context;
	AssetManager assets;
	ChineseHelper helper = ChineseHelper.getInstance();
	ChineseCharacter currentCharacter;
	Stroke currStroke;
	Bitmap currBitmap;

	ChineseCharacter[] chineseCharacters;
	HttpConnector httpConnector;
	SharedPreferences pref;
	SharedPreferences.Editor editor;
	
	private int width;
	private int height;

	float mX;
	float mY;
	
	private Random randGenerator = new Random(System.currentTimeMillis());

	// Delegator of Constructor
	private void initView(Context context) {
		this.context = context;
		pref = context.getSharedPreferences(Key.prefKey, Context.MODE_PRIVATE);
		editor = pref.edit();
		httpConnector = HttpConnector.getInstance();
		chineseBlush = new Paint();
		mPath = new Path();
		assets= context.getResources().getAssets();

		chineseBlush.setAntiAlias(true);
		chineseBlush.setAlpha(alpha);
		chineseBlush.setColor(Color.GRAY);
		chineseBlush.setStrokeWidth(strokeWidth);
		chineseBlush.setStyle(Paint.Style.STROKE);
		chineseBlush.setStrokeCap(Paint.Cap.ROUND);
		
		chineseCharacters = new ChineseCharacter[50];
		currentCharacter = chineseCharacters[0];
		initilize();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		showImage(canvas);
		render(canvas);
	}
	
	private void showImage(Canvas canvas){
		if(currBitmap == null) return;
		canvas.drawBitmap(currBitmap, 0, 0, null);
	}

	private void render(Canvas canvas) {
		canvas.drawPath(mPath, chineseBlush);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getAction();
		float eventX = event.getX();
		float eventY = event.getY();
		
		int x = (int) eventX;
		int y = (int) eventY;
		
		if(currBitmap == null) return false;
		
		if(x < 0 || y < 0){
			return false;
		}else if(x > width-10 || y > width-25){
			return false;
		}
		
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			if(!checkInitPoint(x, y)){
				resetCurrentProblem();
			}else{
				Log.d(TAG, "init point");
				checkInitPoint = true;
				mPath.moveTo(eventX, eventY);
			};
			break;

		case MotionEvent.ACTION_MOVE:
			if(checkInitPoint && checkFinalPoint(x, y)){
				currStroke = currentCharacter.nextStroke();
				if(currStroke.isLastStroke() || currStroke == null){
					nextProblemSendState(width,height);
				}else{
					currBitmap = currStroke.getBitmap();
				}
				resetCurrentProblem();
				invalidate();
				return true;
			}
			if((checkInitPoint(x, y) || checkCenterPoint(x, y) || checkFinalPoint(x, y)) && checkInitPoint == true){
				Log.d(TAG, "center point");
				checkCenterPoint = true;
				mPath.lineTo(eventX, eventY);
			}else if(checkFinalPoint == true){
				
			}else{
				resetCurrentProblem();
			}
			break;
		default:
			Log.d(TAG, "action default");
			break;
		}
		invalidate();
		return true;
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
	    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
	    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
	    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
	    width = widthSize;
	    height = heightSize;
	    
	    setMeasuredDimension(width, width);
	    nextProblem(width, height);
	}
	
	public void closeBitmaps(){
		if(chineseCharacters != null){
			for(ChineseCharacter character : chineseCharacters){
				if(character != null)
					character.freeBitmap();
			}
		}
	}
	
	private void nextProblem(int width, int height){
		if(currentCharacter!=null) currentCharacter.freeBitmap(); // 메모리를 위하여 Free...
		int curIndex = randGenerator.nextInt(maxCount);
		currentCharacter = chineseCharacters[curIndex];
		currentCharacter.loadBitmap(assets, width, height);
		currStroke = currentCharacter.getFirstStroke();
		currBitmap = currStroke.getBitmap();
		nextChineseListener.nextChinese(currentCharacter.getMeaning(), currentCharacter.getLevel());
	}
	
	private void nextProblemSendState(int width, int height){
		nextProblem(width, height);
		sendChineseState();
	}
	
	private void sendChineseState(){
		/*Intent intent = new Intent(context, ChoiceActivity.class);
		intent.putExtra(ChoiceActivity.Path, currentCharacter.getPath());
		intent.putExtra(ChoiceActivity.Count, currentCharacter.getCount());
		intent.putExtra(ChoiceActivity.Answer, currentCharacter.getMeaning());
		
		int[] randomVar = new int[]{0,0,0};
		for(int i=0; i<3; i++){
			int gen = randGenerator.nextInt(maxCount);
			randomVar[i] = gen;
			for(int j=0; j<randomVar.length; j++){
				if(i==j) continue;
				if(randomVar[i] == randomVar[j]){
					i--;
					break;
				}
			}
		}
		
		String noAnswer1 = chineseCharacters[randomVar[0]].getMeaning();
		String noAnswer2 = chineseCharacters[randomVar[1]].getMeaning();
		String noAnswer3 = chineseCharacters[randomVar[2]].getMeaning();
		
		intent.putExtra(ChoiceActivity.NoAnswer1, noAnswer1);
		intent.putExtra(ChoiceActivity.NoAnswer2, noAnswer2);
		intent.putExtra(ChoiceActivity.NoAnswer3, noAnswer3);
		((Activity) context).startActivityForResult(intent, ChoiceActivity.CHOICE_ACTIVITY);*/
	}
	
	
	private void resetCurrentProblem(){
		mPath.reset();
		checkInitPoint = false;
		checkCenterPoint = false;
		checkFinalPoint = false;
	}
	
	private boolean checkFinalPoint(int x, int y){
		boolean result = true;
		int[] bitmapRGB = getRGB(x, y);
		for(int i=0; i<bitmapRGB.length; i++){
			if(bitmapRGB[i] != finalRGB[i]){
				result = false;
				break;
			}
		}
		return result;
	}
	
	private boolean checkCenterPoint(int x, int y){
		boolean result = true;
		int[] bitmapRGB = getRGB(x, y);
		for(int i=0; i<bitmapRGB.length; i++){
			if(bitmapRGB[i] != centerRGB[i]){
				result = false;
				break;
			}
		}
		return result;
	}

	private boolean checkInitPoint(int x, int y) {
		boolean result = true;
		int[] bitmapRGB = getRGB(x, y);
		for(int i=0; i<bitmapRGB.length; i++){
			if(bitmapRGB[i] != initRGB[i]){
				result = false;
				break;
			}
		}
		return result;
	}
	
	private int[] getRGB(int x, int y){
		Log.e(TAG, "(" + x + ", " + y + ") in getRGB"); // (751, 673), (678,739)
		int pixel = currBitmap.getPixel(x, y);
		int red = Color.red(pixel);
		int blue = Color.blue(pixel);
		int green = Color.green(pixel);
		int[] returnValue = new int[]{red, blue, green};
		Log.e(TAG, "(" + red + ", " + blue + ", " + green + ")");
		return returnValue;
	}

	public void initilize() {
		String path = "blue_chung";
		String meaning = "푸를 청";
		String level = "8";
		int count = 9;
		chineseCharacters[0] = new ChineseCharacter(path, meaning, level, count);
		
		path = "military_goon";
		meaning = "군사 군";
		level = "8";
		count = 10;
		chineseCharacters[1] = new ChineseCharacter(path, meaning, level, count);
		
		path = "born_seng";
		meaning = "날 생";
		level = "8";
		count = 6;
		chineseCharacters[2] = new ChineseCharacter(path, meaning, level, count);
		
		path = "brother_hyong";
		meaning = "형 형";
		level = "8";
		count = 6;
		chineseCharacters[3] = new ChineseCharacter(path, meaning, level, count);
		
		path = "day_il";
		meaning = "날 일";
		level = "8";
		count = 5;
		chineseCharacters[4] = new ChineseCharacter(path, meaning, level, count);
		path = "dirt_to";
		meaning = "흙 토";
		level = "8";
		count = 4;
		chineseCharacters[5] = new ChineseCharacter(path, meaning, level, count);
		path = "door_moon";
		meaning = "문 문";
		level = "8";
		count = 9;
		chineseCharacters[6] = new ChineseCharacter(path, meaning, level, count);

		path = "east_dong";
		meaning = "동녘 동";
		level = "8";
		count = 9;
		chineseCharacters[7] = new ChineseCharacter(path, meaning, level, count);

		path = "eight_par";
		meaning = "여덟 팔";
		level = "8";
		count = 3;
		chineseCharacters[8] = new ChineseCharacter(path, meaning, level, count);

		path = "father_boo";
		meaning = "아버지 부";
		level = "8";
		count = 5;
		chineseCharacters[9] = new ChineseCharacter(path, meaning, level, count);

		path = "fire_ha";
		meaning = "불 화";
		level = "8";
		count = 5;
		chineseCharacters[10] = new ChineseCharacter(path, meaning, level,
				count);

		path = "first_sun";
		meaning = "먼저 선";
		level = "8";
		count = 7;
		chineseCharacters[11] = new ChineseCharacter(path, meaning, level,
				count);

		path = "five_oh";
		meaning = "다섯 오";
		level = "8";
		count = 5;
		chineseCharacters[12] = new ChineseCharacter(path, meaning, level,
				count);

		path = "four_sa";
		meaning = "넉 사";
		level = "8";
		count = 6;
		chineseCharacters[13] = new ChineseCharacter(path, meaning, level,
				count);

		path = "home_sil";
		meaning = "집 실";
		level = "8";
		count = 10;
		chineseCharacters[14] = new ChineseCharacter(path, meaning, level,
				count);

		path = "human_in";
		meaning = "사람 인";
		level = "8";
		count = 3;
		chineseCharacters[15] = new ChineseCharacter(path, meaning, level,
				count);

		path = "iron_gum";
		meaning = "쇠 금";
		level = "8";
		count = 9;
		chineseCharacters[16] = new ChineseCharacter(path, meaning, level,
				count);

		path = "king_wang";
		meaning = "임금 왕";
		level = "8";
		count = 4;
		chineseCharacters[17] = new ChineseCharacter(path, meaning, level,
				count);

		path = "kinship_chone";
		meaning = "마디 촌";
		level = "8";
		count = 4;
		chineseCharacters[18] = new ChineseCharacter(path, meaning, level,
				count);

		path = "korea_han";
		meaning = "한국 한";
		level = "8";
		count = 18;
		chineseCharacters[19] = new ChineseCharacter(path, meaning, level,
				count);

		path = "long_jang";
		meaning = "길 장";
		level = "8";
		count = 9;
		chineseCharacters[20] = new ChineseCharacter(path, meaning, level,
				count);

		path = "mather_mo";
		meaning = "어머니 모";
		level = "8";
		count = 6;
		chineseCharacters[21] = new ChineseCharacter(path, meaning, level,
				count);

		path = "moon_wall";
		meaning = "푸를 청";
		level = "8";
		count = 5;
		chineseCharacters[22] = new ChineseCharacter(path, meaning, level,
				count);

		path = "nine_goo";
		meaning = "아홉 구";
		level = "8";
		count = 3;
		chineseCharacters[23] = new ChineseCharacter(path, meaning, level,
				count);

		path = "north_book";
		meaning = "북녘 북";
		level = "8";
		count = 6;
		chineseCharacters[24] = new ChineseCharacter(path, meaning, level,
				count);

		path = "one_il";
		meaning = "하나 일";
		level = "8";
		count = 2;
		chineseCharacters[25] = new ChineseCharacter(path, meaning, level,
				count);

		path = "school_kyo";
		meaning = "학교 교";
		level = "8";
		count = 11;
		chineseCharacters[26] = new ChineseCharacter(path, meaning, level,
				count);

		path = "seven_chil";
		meaning = "일곱 칠";
		level = "8";
		count = 3;
		chineseCharacters[27] = new ChineseCharacter(path, meaning, level,
				count);

		path = "six_uke";
		meaning = "여섯 육";
		level = "8";
		count = 5;
		chineseCharacters[28] = new ChineseCharacter(path, meaning, level,
				count);

		path = "small_so";
		meaning = "작을 소";
		level = "8";
		count = 4;
		chineseCharacters[29] = new ChineseCharacter(path, meaning, level,
				count);

		path = "south_nam";
		meaning = "남녘 남";
		level = "8";
		count = 10;
		chineseCharacters[30] = new ChineseCharacter(path, meaning, level,
				count);

		path = "studey_hunk";
		meaning = "배울 학";
		level = "8";
		count = 17;
		chineseCharacters[31] = new ChineseCharacter(path, meaning, level,
				count);

		path = "subjects_min";
		meaning = "백성 민";
		level = "8";
		count = 6;
		chineseCharacters[32] = new ChineseCharacter(path, meaning, level,
				count);

		path = "ten_sheep";
		meaning = "열 십";
		level = "8";
		count = 3;
		chineseCharacters[33] = new ChineseCharacter(path, meaning, level,
				count);

		path = "ten_thousand_man";
		meaning = "일만 만";
		level = "8";
		count = 14;
		chineseCharacters[34] = new ChineseCharacter(path, meaning, level,
				count);

		path = "tomb_san";
		meaning = "뫼 산";
		level = "8";
		count = 4;
		chineseCharacters[35] = new ChineseCharacter(path, meaning, level,
				count);

		path = "tree_mok";
		meaning = "나무 목";
		level = "8";
		count = 5;
		chineseCharacters[36] = new ChineseCharacter(path, meaning, level,
				count);

		path = "two_lee";
		meaning = "두 이";
		level = "8";
		count = 3;
		chineseCharacters[37] = new ChineseCharacter(path, meaning, level,
				count);

		path = "water_su";
		meaning = "물 수";
		level = "8";
		count = 5;
		chineseCharacters[38] = new ChineseCharacter(path, meaning, level,
				count);

		path = "white_baek";
		meaning = "흰 백";
		level = "8";
		count = 6;
		chineseCharacters[39] = new ChineseCharacter(path, meaning, level,
				count);

		path = "woman_yer";
		meaning = "여자 녀";
		level = "8";
		count = 4;
		chineseCharacters[40] = new ChineseCharacter(path, meaning, level,
				count);

		path = "year_nyon";
		meaning = "해 년";
		level = "8";
		count = 7;
		chineseCharacters[41] = new ChineseCharacter(path, meaning, level,
				count);

		path = "younger_brother_je";
		meaning = "아우 제";
		level = "8";
		count = 8;
		chineseCharacters[42] = new ChineseCharacter(path, meaning, level,
				count);

		path = "outside_woe";
		meaning = "바깥 외";
		level = "8";
		count = 6;
		chineseCharacters[43] = new ChineseCharacter(path, meaning, level,
				count);

		path = "center_joong";
		meaning = "가운데 중";
		level = "8";
		count = 5;
		chineseCharacters[44] = new ChineseCharacter(path, meaning, level,
				count);

		path = "big_dae";
		meaning = "클 대";
		level = "8";
		count = 4;

		chineseCharacters[45] = new ChineseCharacter(path, meaning, level,
				count);
		path = "teach_kyo";
		meaning = "가르칠 교";
		level = "8";
		count = 12;
		chineseCharacters[46] = new ChineseCharacter(path, meaning, level,
				count);
		
		path = "three_sam";
		meaning = "석 삼";
		level = "8";
		count = 4;
		chineseCharacters[47] = new ChineseCharacter(path, meaning, level,
				count);
		
		path = "west_se";
		meaning = "서녘 서";
		level = "8";
		count = 7;

	}

	// Constructors for draw main board that call initView()
	public DrawMainBoard(Context context) {
		super(context);
		initView(context);
	}

	public DrawMainBoard(Context context, AttributeSet attrs) {
		super(context, attrs, 0);
	}

	public DrawMainBoard(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
}
